package jpb.security;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * Created by haol on 2017/4/20.
 */
public class ProduceJwt {
        private HandleToken handleToken = new HandleToken();

        public JwtBuilder createJwtBuilder(String jwtId, String subject, Date IssuedTime) {
                SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
                SecretKey key = handleToken.generalKey();
                JwtBuilder jwtBuilder = Jwts.builder();
                jwtBuilder.setHeaderParam("tye", "jwt");
                jwtBuilder.setHeaderParam("alg", "HS256");
                jwtBuilder.setId(jwtId);
                if (this.isSetIssuedAt()){
                        jwtBuilder.setIssuedAt(IssuedTime);//签发时间
                }

                jwtBuilder.setSubject(subject);//接受主体，此处为登录的用户
                jwtBuilder.signWith(signatureAlgorithm, key);//加密
                return jwtBuilder;
        }

        public String produceWebToken(String subject, String jwtId, long JwtTtlMillis,Date IssuedTime) {
                JwtBuilder jwtBuilder = this.createJwtBuilder(jwtId, subject,IssuedTime);
                jwtBuilder.setIssuer("web");//签发者
                if (JwtTtlMillis > 0) {
                        long expMillis = System.currentTimeMillis() + JwtTtlMillis;
                        Date exp = new Date(expMillis);
                        jwtBuilder.setExpiration(exp);
                }
                return jwtBuilder.compact();

        }

        public String produceAppToken(String jwtId, String subject, long JwtTtlMillis,Date IssuedTime) {
                JwtBuilder jwtBuilder = this.createJwtBuilder(jwtId, subject,IssuedTime);
                jwtBuilder.setIssuer("app");//签发者
                if (JwtTtlMillis > 0) {
                        long expMillis = System.currentTimeMillis() + JwtTtlMillis;
                        Date exp = new Date(expMillis);
                        jwtBuilder.setExpiration(exp);
                }
                return jwtBuilder.compact();
        }
        public boolean isSetIssuedAt(){
                return true;
        }
}
